<?php
/**
 * 公共函数,无需操作权限限制
 */
class PublicApp extends Controller {

    /**
     * 用户登录
     */
    public function loginAct() {
        if($_POST){
            $username = I('post.username');
            //判断 用户名是否为空
            if(empty($username))
                $this->ajaxReturn(300,'用户名不能为空!');
            //判断 密码是否为空
            if(empty($_POST['password']))
                $this->ajaxReturn(300,'密码不能为空!');
            $verify = new Verify();
            if(!$verify->check(My::arr2var($_POST,'verify')))
                $this->ajaxReturn(300,'验证码错误!');
            $user = DB('user')->where("username='{$username}' AND password='".md5(md5($_POST['password']))."'")->field('id,publish')->find();
            if(is_array($user)){
                if($user['publish']=='0') $this->ajaxReturn(300,'用户已被禁用!');
                $ok = self::doLogin($user['id'],'default');
                if($ok)
                    $this->ajaxReturn(200,'登陆成功!!');
                else
                    $this->ajaxReturn(300,'登陆失败（设置登录状态时异常）');
            }else{
                $this->ajaxReturn(300,'用户名或密码错误!');
            }
        }else{
            if(!My::user('userid') OR !My::user('username')){
                //第三登陆url
                $show_oauth = My::alias2field('config','admin','params.show_oauth');
                $this->assign('show_oauth',$show_oauth);
                if($show_oauth){
                    $this->assign('weixin_url',Oauth2::getInstance()->loginURL('weixin'));
                    $this->assign('qq_url',Oauth2::getInstance()->loginURL('qq'));
                    $this->assign('sina_url',Oauth2::getInstance()->loginURL('sina'));
                }
                $this->display('include/login');
            }else{
                $this->redirect('./');
            }
            
        }
    }
    
    /**
     * 设置登录状态数据操作
     * @param int $userid 用户id
     * @param string $login_type 登录类型
     */
    private function doLogin($userid, $login_type='default'){
        if(!My::is_id($userid)) return false;
        $result['userid'] = $userid;
        $result['login_type'] = $login_type;
        //获得当前用户数据
        $temp = DB('user')->field('password',true)->where("id={$userid}")->find();
        if(!is_array($temp)) return false;
        $temp['params'] = My::decodeJson($temp['params']);
        //添加上一次登录的在线时长纪录
        self::setOnline($userid);
        //更新当前登录IP/登录时间/登出时间
        DB('user')->field('login_ip,login_time,loginout_time')->where("id={$userid}")->save(array('login_ip'=>get_client_ip(), 'login_time'=>date('Y-m-d H:i:s'), 'loginout_time'=>date('Y-m-d H:i:s')));
        //登录次数++
        DB('user')->where('id='.$userid)->setInc('hit');
        //读取当前角色用户数据
        $role_info = DB('role')->field('name,module_ids')->where("id={$temp['role_id']}")->find();
        $temp['role_name'] = $role_info['name'];
        $temp['role_module'] = $role_info['module_ids'];//角色菜单权限(逗号分隔)
        //有userid就行了,id就不要了
        unset($temp['id']);
        //merge
        $result = array_merge($result,$temp);
        //设置当前用户登录session数据
		$_SESSION = (!empty($_SESSION) AND is_array($_SESSION))?array_merge($_SESSION,$result):$result;
        //记录访问日志
        M('admin.visit')->setVisitLog('登陆成功');
        return true;
    }
    /**
     * 添加上一次登录的在线时长记录
     */
    private function setOnline($userid=0){
        if(!My::is_id($userid)) return false;
        //对应user表数据
        $temp = DB('user')->where("id={$userid}")->find();
        //用户id
        $result['uid'] = $userid;
        //上次登录时间
        $result['login_time'] = strtotime($temp['login_time']);
        //上次退出时间
        $result['loginout_time'] = strtotime($temp['loginout_time']);
        //在线时长(小时)
        $result['length'] = ($result['loginout_time']-$result['login_time'])/60/60;
        //登录IP
        $result['login_ip'] = $temp['login_ip'];
        //记录添加时间
        $result['adddate'] = time();
        //print_r($temp);exit;
        DB('online')->clear()->add($result);
    }
    
    /**
     * 第三方登录用户绑定
     */
    public function bindAct(){
        if($_POST){
            self::binding(My::arr2var($_POST,'type'),I('post.username'),My::arr2var($_POST,'password'));
        }else{
            $oauth_type=C('oauth_type');
            $type = My::arr2var($_GET,'type');
            if(!in_array(strtoupper($type), Oauth2::getInstance()->getOauthType()))
                $this->ajaxReturn(404,'未知的第三方登录类型！');
            $openid = My::arr2var($_SESSION,$type.'OauthCache.openid');
            $nickname = My::arr2var($_SESSION,$type.'OauthCache.nickname');
            if(!$openid)
                $this->ajaxReturn(404,'获取'.$oauth_type[$type].'用户信息失败！');
            $member = DB('user')->where("openid_{$type}='{$openid}'")->find();
            //已经绑定了一个帐号
            if($member){
                self::doLogin($member['id'],$type);
                redirect('/admin/');
            }
            //未绑定
            else{
                $this->assign('oauthNickname',My::arr2var($_SESSION,$type.'OauthCache.nickname'));
            }
        }
        //display
        $this->display('include/bind');
    }
    /**
     * 绑定绑号
     */
    private function binding($type,$username,$password){
        if(!in_array(strtoupper($type),Oauth2::getInstance()->getOauthType()))
            $this->ajaxReturn(300,'未知的第三方登录类型!');
        $oauth_type=C('oauth_type');
        if(!My::arr2var($_SESSION,$type.'OauthCache'))
            $this->ajaxReturn(300,'无法读取'.$oauth_type[$type].'用户信息!');
        if($username=='')
            $this->ajaxReturn(300,'用户名不能为空!');
        if($password=='')
            $this->ajaxReturn(300,'密码不能为空!');
        //验证码
        $verify = new Verify();
        if(!$verify->check(My::arr2var($_POST,'verify')))
            $this->ajaxReturn(300,'验证码有误!');
        $password =  md5(md5($password));
        $nickname = My::arr2var($_SESSION,$type.'OauthCache.nickname');
        //过滤掉昵称中的非UTF-8的字符
        $nickname = M('admin.helper')->filter_utf8_char($nickname);
        $result = DB('user')->where("username='{$username}' AND password='{$password}' AND publish=1")->find();
        if($result){
            $openid = My::arr2var($_SESSION,$type.'OauthCache.openid');
            if(My::arr2var($result,'openid_'.$type)!='')
                $this->ajaxReturn(300,'该帐号已经绑定了一个'.$oauth_type[$type].'用户!');
            $params = My::decodeJson($result['params']);
            $params['nickname'][$type] = $nickname;
            $data['openid_'.$type] = My::arr2var($_SESSION,$type.'OauthCache.openid');
            $data['params'] = $params;
            $ok = DB('user')->where("id={$result['id']}")->clear()->save($data);
            if($ok){
                unset($_SESSION[$type.'OauthCache']);
                self::doLogin($result['id'],$type);
                $this->ajaxReturn(200,'绑定成功！');
            }else{
                $this->ajaxReturn(300,'db错误');
            }
        }else{
            $this->ajaxReturn(300,'用户名或密码错误!');
        }
    }

    /**
     * 用户退出
     */
    public function logoutAct() {
        //删除本系统的session
        Session::destory();
        redirect(Router::encodeUrl('index.php?app=public&act=login'));
    }
    
    /**
     * 获取验证码
     */
    public function getVerifyCodeAct(){
        $config = array('imageW'=>100,'imageH'=>30,'fontSize'=>14,'useNoise'=>false,'fontttf'=>'5.ttf','length'=>4);
        $verify = new Verify($config);
        $verify->entry();
    }

    /**
     * 跳转函数(兼容函数)
     * by huanran.zhao
     */
    public function ajaxReturn($statusCode, $message, $callbackType = '', $forwardUrl = '', $data='') {
        //404页面,使用方法$this->ajaxReturn(404,'找不到页面');
        if($statusCode==404){
            $this->assign('title',$message);
            $this->display('include/404');
            exit();
        }
        $jsonData = array(
                'statusCode' => $statusCode,
                'message' => $message,
                'forwardUrl' => $forwardUrl,
                'data' => $data
            );
        exit(json_encode($jsonData));
    }

}